package tool.soft

import java.io.File
import command.CommandExec
import dao._
import models.Tables
import org.joda.time.DateTime
import play.api.mvc.{AnyContent, Request}
import play.twirl.api.Html
import shared.Pojo._
import tool.Pojo._
import tool._
import tool.plot.AllPlot._
import tool.plot._
import tool.soft.AllSoft.SoftBT
import implicits.Implicits._
import models.Tables._
import play.api.data.FormBinding
import play.api.i18n.Messages
import tool.softT.PcaSoftBT
import utils.Utils
import upickle.default._

/**
 * Created by yz on 16/9/2020
 */
object PcaSoft extends PcaSoftBT with SoftBT {

  override def getResultHtml(missionId: Int)(implicit request: Request[AnyContent], messages: Messages): Html = {
    views.html.user.mission.pcaResult(missionId)
  }

  override def produceConfigFile(workspaceDir: File, index: Int)(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    Utils.t2ConfigFile(data, Tool.getCalculateConfigJsonFile(workspaceDir))
    Utils.t2ConfigFile(workspaceDir, data)
    super.producePlotConfigFile(workspaceDir, index)
  }

  def getArg(implicit request: Request[AnyContent], messages: Messages, formBinding: FormBinding): ujson.Value = {
    val groupNum = Tool.getGroupNum(userId, data.groupFile)
    val scaleMethodMap = Tool.getScaleMethodMap
    val basicJson = ujson.Obj(messages("scaleMethod") -> scaleMethodMap(data.scaleMethod))
    basicJson ++ {
      groupNum match {
        case x if x == 2 => ujson.Obj(messages("paired") -> Tool.getIsPairedStr(data.isPaired))
        case x => ujson.Obj()
      }
    }
  }


  override def getHtml(missionName: String, missionId: Option[Int])(implicit request: Request[AnyContent], messages: Messages): Html = {
    views.html.user.soft.pca(missionName, missionId)
  }

  override def getMission(implicit request: Request[AnyContent], matrixFileDataDao: MatrixFileDataDao, messages: Messages, formBinding: FormBinding): Tables.MissionRow = {
    val input = if (data.hasGroup) {
      List(data.file, data.groupFile)
    } else List(data.file)
    MissionRow(id = 0, missionName = s"${data.missionName}", kind = nameStr, userId = userId,
      startTime = new DateTime(), state = "preparing", arg = getArg, input = input)
  }

  override def produceInputFile(workspaceDir: File)(implicit request: Request[AnyContent], dao: MyDao, formBinding: FormBinding): Any = {
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    Tool.produceRawMetaboliteFile(userId, data.file, rawDataFile)
    val groupFile = new File(workspaceDir, "group.txt")
    if (data.hasGroup) {
      Tool.produceRawGroupFile(userId, data.groupFile, rawDataFile, groupFile)
    } else {
      Tool.produceNoGroupFile(rawDataFile, groupFile)
    }
  }

  override def data(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    FormTool.pcaForm.bindFromRequest().get
  }


}
